package cn.gov.pbc.dream.util;

import java.math.BigDecimal;

public class BigDecimalUtil {

    private static final int scale = 2;

    public static final BigDecimal add(BigDecimal a, BigDecimal b) {
        if (a == null && b == null) {
            return new BigDecimal("0").setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
        if (a == null) {
            return b.setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
        if (b == null) {
            return a.setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
        return a.add(b).setScale(scale, BigDecimal.ROUND_HALF_UP);
    }

    public static final BigDecimal sub(BigDecimal a, BigDecimal b) {
        if (a == null && b == null) {
            return new BigDecimal("0").setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
        if (a == null) {
            return b.negate().setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
        if (b == null) {
            return a.setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
        return (a.subtract(b)).setScale(scale, BigDecimal.ROUND_HALF_UP);
    }

    public static final BigDecimal mul(BigDecimal a, BigDecimal b){
        if (a == null || b == null) {
            return new BigDecimal("0").setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
        return (a.multiply(b)).setScale(scale, BigDecimal.ROUND_HALF_UP);
    }

    public static int compare(BigDecimal a, BigDecimal b) {
        a = a.setScale(scale, BigDecimal.ROUND_HALF_UP);
        b = b.setScale(scale, BigDecimal.ROUND_HALF_UP);
        return a.compareTo(b);
    }

    public static boolean compareBand(BigDecimal target, BigDecimal base, BigDecimal factor){
        BigDecimal zero = new BigDecimal("0").setScale(scale, BigDecimal.ROUND_HALF_UP);
        BigDecimal one = new BigDecimal("1").setScale(scale, BigDecimal.ROUND_HALF_UP);
        if(target == null){
            target = zero;
        } else {
            target = target.setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
        if(base == null){
            base = zero;
        } else {
            base = base.setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
        if(factor == null){
            factor = zero;
        } else {
            factor = factor.setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
        BigDecimal upFactor = BigDecimalUtil.add(factor, one);
        BigDecimal downFactor = BigDecimalUtil.sub(one, factor);
        BigDecimal upBase = BigDecimalUtil.mul(base, upFactor);
        BigDecimal downBase = BigDecimalUtil.mul(base, downFactor);
        if(target.compareTo(upBase) <= 0 && target.compareTo(downBase) >= 0){
            return true;
        }
        return false;
    }
}
